package file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import operator.Handler;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import common.Constant;
import common.Singleton;
import view.Main;
import vo.Mean;

public class XMLOperator {

    private Main m;

    private static XMLOperator xmlOperator;
    private XMLOperator() {}
    public static XMLOperator getOperator() {
        if(xmlOperator == null) {
            xmlOperator = new XMLOperator();
            xmlOperator.m = Singleton.main();
        }
        return xmlOperator;
    }

    private Handler handler = Singleton.handler();
    /**
     * 导入XML，需确保文章与其对应
     */

    public void readXML() {
        File selected = Singleton.fUtil().findFile("xml");
        if (selected == null)
            return;
        handler.clear(false);
        try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(selected);
            Element root = doc.getRootElement();
            List<Element> cs = root.getChildren();
            Mean main = null;

            String version = root.getAttributeValue("version"), page = root.getAttributeValue("page"),
                    care = root.getAttributeValue("care");
            for (Element now : cs) {
                if (now.getName().equals("main")) {
                    main = setMeanInXML(now, null, version);
                    main.setDescription();
                } else if (now.getName().equals("vice")) {
                    Mean vice = setMeanInXML(now, main, version);
                    vice.setDescription();
                }
            }
            if (page != null) {
                m.recordPage = m.presentPage = Integer.parseInt(page);
                handler.getM().jtfPrePgPgSet(m.presentPage);
            }
            if (care != null) {
                handler.getText().setCaretPosition(m.recordCarePosition = Integer.parseInt(care));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        Singleton.vc().attr_addAll();
    }

    /**
     * 读取XML中的意象单元
     */
    private Mean setMeanInXML(Element e, Mean main, String version) {
        List<Element> cs = e.getChildren();
        Mean mean = null;
        String text = e.getAttributeValue("text");
        for (Element now : cs) {
            if (now.getName().equals("location")) {
                if (mean == null) {
                    if (main == null)
                        mean = new Mean(text, Integer.parseInt(now.getAttributeValue("from")), handler.getGroupId());
                    else
                        mean = main.addNext(text, Integer.parseInt(now.getAttributeValue("from")));
                } else
                    mean.setLocation(Integer.parseInt(now.getAttributeValue("from")));
            } else if (now.getName().equals("attr")) {// 读入XML属性信息

                for (int o = 1; o < m.pointed_attrs.size() + 1; o++) {
                    if (now.getAttributeValue("t" + o) != null)
                        mean.setPointedAttr(now.getAttributeValue("t" + o), o, version);
                }
            }
        }
        return mean;
    }

    /**
     * 写入XML，不保存源文件。 使数据可用，则不能改变源文件。
     */
    void writeXML(File out) {
        if (out == null)
            return;

        Singleton.fUtil().setMeanTree();
        Element root = new Element("Chain");
        root.setAttribute("version", Constant.ATTR_VERSION);
        root.setAttribute("page", m.presentPage + "");
        root.setAttribute("care", handler.getText().getCaretPosition() + "");
        Document d = new Document(root);
        for (Mean aMainMean : handler.mainMean) {
            Element main = new Element("main");
            Mean next = aMainMean;
            addAttribute(next, main);
            root.addContent(main);
            while (next.getNext() != null) {
                Element vice = new Element("vice");
                next = next.getNext();
                addAttribute(next, vice);
                root.addContent(vice);
            }
        }

        // 填入Format参数可以在TXT等编辑器下自动换行显示
        XMLOutputter XMLOut = new XMLOutputter(Format.getPrettyFormat());
        try {
            XMLOut.output(d, new FileOutputStream(out));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 向XML中添加属性
     */
    private static void addAttribute(Mean m, Element e) {
        e.setAttribute("text", m.getText());
        Element location = new Element("location");
        location.setAttribute("from", m.getLocation() + "");
        e.addContent(location);

        String attributes[] = m.getAttributes();
        // CTCRE1.0 写入属性
        Element attr = new Element("attr");
        for (int i = 0; i < attributes.length; i++) {
            if (!attributes[i].equals("")) {
                attr.setAttribute("t" + (i + 1), attributes[i]);
            }
        }
        attr.setAttribute("index", m.index_in_full_text + "");// 全文中排序
        e.addContent(attr);
    }
//	public static void main(String args[]){
//		Attr a=readFolderLine("#词语类型：【名词：专名-全名、专名-姓、【专名-名：专名-字】专名-号、专名-谥号、专名-国名+谥号、光杆名词、无定名词短语、有定名词短语】【指示词：远称指示词、近称指示词、远称指示词+名词短语、近称指示词+名词短语】【代词：人称代词、有生命代词、无生命代词、反身代词、代词+反身代词】零形代词",1);
//		System.out.println(readFolders(a.getFolders()));
//	}
}
